package com.example.myapp61.Mfragment;

import android.animation.ValueAnimator;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.OvershootInterpolator;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.airbnb.lottie.LottieAnimationView;
import com.ejlchina.okhttps.HTTP;
import com.example.myapp61.Mfragment.Home.XList;
import com.example.myapp61.Util.ScreenUtils;
import com.example.myapp61.xiaoye.top.Dialog_1;
import com.example.myapp61.Mfragment.Home.SmartAdapter;
import com.example.myapp61.MySqlDB.DBMainHepler;
import com.example.myapp61.R;
import com.example.myapp61.Util.HttpUtil;
import com.example.myapp61.Util.ParameUtil;
import com.example.myapp61.Util.ToasUtil;
import com.scwang.smart.refresh.layout.api.RefreshFooter;
import com.scwang.smart.refresh.layout.api.RefreshHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.constant.RefreshState;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnMultiListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import org.json.JSONException;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;

import jp.wasabeef.recyclerview.adapters.AlphaInAnimationAdapter;
import jp.wasabeef.recyclerview.adapters.ScaleInAnimationAdapter;
import jp.wasabeef.recyclerview.animators.SlideInLeftAnimator;

import static android.content.ContentValues.TAG;

public class fragment1 extends Fragment {
    private DBMainHepler dbMainHepler;
    private SQLiteDatabase db;
    private CHandler h = new CHandler();
    private ArrayList lists;
    private int ispage=0;
    private SmartAdapter smartAdapter;
    private RecyclerView recyclerView;
    private Dialog_1 mDialog_1;
    private Context mContext;
    private boolean mIsRefreshing;
    private RefreshLayout mRefreshLayout;

    private LottieAnimationView mLottieAnimationView;

    HTTP http = HTTP.builder()
            .callbackExecutor((Runnable run) -> {
                // 实际编码中可以吧 Handler 提出来，不需要每次执行回调都重新创建
                new Handler(Looper.getMainLooper()).post(run); // 在主线程执行
            })
            .baseUrl("https://yeqt.top:3005/ago")
            .build();


    //获取Content
    @Override
    public void onAttach(@NonNull Context context) {
        Log.i(TAG, "onAttach: "+"我只被调用一次");

        super.onAttach(context);
        dbMainHepler =  new DBMainHepler(context,"Test15.db",null,1);
        smartAdapter = new SmartAdapter(context,dbMainHepler.select("test2",10));
        this.mContext = context;
        initView();
        setClickItem();
    }

    private void setClickItem() {
        /**
         **************************每个item的点击事件
         */
        smartAdapter.setOnItemClick(new SmartAdapter.OnItemClick() {
            @Override
            public void click(View view, int position) {
                ToasUtil.showMes(getContext(),"你点击了第"+position+"个item");
                //startActivity(new Intent(mContext,AllText.class));
                Dialog_1 dialog_1 = new Dialog_1(mContext);
                dialog_1.setTitle("要帮忙吗?")
                        .setMsg("明天见")
                        .setConfirm("确定吗？", new Dialog_1.IOonConfir() {
                            @Override
                            public void oncencel(Dialog_1 dialog_1) {
                                smartAdapter.getDatas2().get(position).getMessages();
                                String id = smartAdapter.getDatas2().get(position).get_id();
                                String res =  http.async("/RelQuer").addBodyPara("data_id",id).post().getResult().getBody().toString();
                                dialog_1.dismiss();
                                xiaoye_RelScc(res,position);
                            }
                        }).show();
                dialog_1.getWindow().setLayout(ScreenUtils.getScreenWidth(mContext)/3*3, LinearLayout.LayoutParams.WRAP_CONTENT);
                dialog_1.getWindow().setBackgroundDrawableResource(R.drawable.my_bg_dialog2);
            }

            private void xiaoye_RelScc(String rel,int position) {
                mDialog_1 = new Dialog_1(mContext);
                mDialog_1.setTitle("获取联系方式成功")
                        .setMsg(rel)
                        .setConfirm("知道了", new Dialog_1.IOonConfir() {
                            @Override
                            public void oncencel(Dialog_1 dialog_1) {
                                mDialog_1.dismiss();
                                smartAdapter.delete(position);
                            }
                        }).show();
            }
            @Override
            public void longClick(View view, int position) {
                ToasUtil.showMes(getContext(),"你长按了第"+position+"个item");
            }
        });
    }

    private void initView() {

    }

    @Nullable
    @Override
    //Fragment被创建时调用
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.i(TAG, "onCreateView: "+"创建fragment时调用，只调用一次");

        View view = inflater.inflate(R.layout.layout_fragment1, null);
        return view;
    }
    //视图创建后调用
    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        Log.i(TAG, "onViewCreated: "+"我被调用了,每次创建View组件是调用回调这个方法");
        mLottieAnimationView = view.findViewById(R.id.tag);
        recyclerView = view.findViewById(R.id.IdRecyclerView);
        mRefreshLayout = view.findViewById(R.id.IdSmart);
        xiaoye_setRecycler(); //RecyclerView
        xiaoye_setRefreshlayout(); //上拉加载，下拉刷新

        mLottieAnimationView.setVisibility(View.GONE);
        mLottieAnimationView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mLottieAnimationView.setProgress(0.56f);
                mLottieAnimationView.resumeAnimation();
            }
        });
        super.onViewCreated(view, savedInstanceState);
    }

    private void xiaoye_setRefreshlayout() {
        mRefreshLayout.autoRefresh();  //自动刷新
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                ispage =0; //刷新时页数清零
                Thread t = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Message message = new Message();
                        message.what = 1;
                        try {
                            //网络请求
                            message.obj = HttpUtil.reqStart();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        h.sendMessage(message);
                        refreshLayout.finishRefresh(000);
                    }
                });
                t.start();
            }
        });

        mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                ispage++;
                Thread t = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Message message = new Message();
                        message.what =2;
                        try {
                            message.obj  = HttpUtil.reqStart(ispage);
                        } catch (IOException | JSONException e) {
                            e.printStackTrace();
                        }
                        h.sendMessage(message);
                        refreshLayout.finishLoadMore(000);
                    }
                });
                t.start();
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void xiaoye_setRecycler() {
        recyclerView.setItemAnimator(new SlideInLeftAnimator());
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        //item设置动画---复合效果
        ScaleInAnimationAdapter scale = new ScaleInAnimationAdapter(smartAdapter);
        scale.setDuration(1000);
        scale.setFirstOnly(false);//动画是否只执行一次
        scale.setInterpolator(new OvershootInterpolator()); //插值器
        recyclerView.setAdapter(new ScaleInAnimationAdapter(scale));

        recyclerView.setOnScrollChangeListener(new RecyclerView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View view, int i, int i1, int i2, int i3) {
//                //获得recyclerView的线性布局管理器
//               LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
//               //获得第一个item的下标,等于0表示可见状态
//               int position = manager.findFirstVisibleItemPosition();
//
//               View find = manager.findViewByPosition(position);
//                Log.i(TAG, "onScrollChange---------------------------------------: "+i3);
//               int height = find.getHeight();
//               int flag = position * height - find.getTop();
               if (i3>30){
                   mLottieAnimationView.playAnimation();
                   mLottieAnimationView.addAnimatorUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                       @Override
                       public void onAnimationUpdate(ValueAnimator valueAnimator) {
                           BigDecimal b = new BigDecimal(valueAnimator.getAnimatedFraction());
                           float m_price = b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
                           if (m_price == 0.55f){
                               mLottieAnimationView.pauseAnimation();
                           }
                           if (valueAnimator.getAnimatedFraction() == 1f){
                               recyclerView.scrollToPosition(0);
                           }
                       }
                   });
                   mLottieAnimationView.setVisibility(View.VISIBLE);
               }
               else if(i3<=0){
                   mLottieAnimationView.setVisibility(View.GONE);
               }
            }
        });
    }

    /**
     * fragment的生命周期
     */

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        Log.i(TAG, "onCreate: "+"启动fragment时回调");
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onResume() {
        Log.i(TAG, "onResume: "+"恢复fragment时回调,onCreate之后一定回调这个方法");
        super.onResume();
    }

    @Override
    public void onPause() {
        Log.i(TAG, "onPause: "+"fragment被暂停了");
        super.onPause();
    }

    @Override
    public void onStop() {
        Log.i(TAG, "onStop: "+"fragment停止了");
        super.onStop();
    }

    /**
     * 内部类
     * 处理网络请求数据
     */
   class CHandler extends Handler{
       @Override
       public void handleMessage(@NonNull Message msg) {
           super.handleMessage(msg);
           if (msg.what ==1){
               /**
                * 数据处理，较难，折磨半天
                * 增加到数据库
                */
               try {
                   ArrayList<XList> arrayList = ParameUtil.test1(msg.obj.toString());
//                   for (int i = 0; i < arrayList.size(); i++) {
//                       Log.d(TAG, "handleMessage: "+arrayList.get(i).getImages().toString());
//                   }
                   smartAdapter.addall(arrayList);
                   dbMainHepler.save("test2",msg.obj.toString());
               } catch (JSONException e) {
                   e.printStackTrace();
               }
           }
           if (msg.what ==2){
               try {
                   /**
                    * 刷新RecyclerView
                    */
                   ArrayList<XList> arrayList = ParameUtil.test1(msg.obj.toString());
                   smartAdapter.saveall(arrayList);
               } catch (JSONException e) {
                   e.printStackTrace();
               }
           }
       }
   }

    private static String getType(Object a) {
        return a.getClass().toString();
    }
}
